from neutron import Plugin, execute, User, OS, Shutil
from fastapi import HTTPException
from server import userdb
from server import vfs
from server import plugin
import sqlite3
import asyncio


def main(app: Plugin):
    @app.route.get("/user", level=2)
    async def get_users(user: User):  # 获取用户列表
        if (not await app.checker.check_func_permission(user, 2, "user")):
            raise HTTPException(status_code=403)
        rets = await userdb.execute("SELECT * FROM users")
        return {
            "code": 0,
            "msg": "",
            "data": [i[0] for i in rets]
        }

    @app.route.post("/user/create", level=2)
    async def create_users(user: User, username: str, passwd: str):  # 创建用户
        if (not await app.checker.check_func_permission(user, 2, "user")):
            raise HTTPException(status_code=403)
        try:
            # 插入
            await userdb.execute("INSERT INTO users (username, password) VALUES (?, ?)", True, (username, userdb.hash_password(passwd)))
        except sqlite3.IntegrityError:
            return {
                "code": 1,
                "msg": "用户名已存在"
            }
        return {
            "code": 0,
            "msg": ""
        }

    @app.route.post("/user/delete", level=2)
    async def delete_users(user: User, username: str):  # 删除用户
        os = OS(user)
        shutil = Shutil(user)
        if (not await app.checker.check_func_permission(user, 2, "user")):
            raise HTTPException(status_code=403)
        ret = await userdb.execute_rc("DELETE FROM users WHERE username = ?", True, (username,))
        if username in vfs.users_permission_cache:  # 删除缓存
            del vfs.users_permission_cache[username]
        if (await os.path.exists("config"+os.sep+"session"+os.sep+username)):
            asyncio.create_task(shutil.rmtree(
                "config"+os.sep+"session"+os.sep+username))
        if (ret == 0):
            return {
                "code": 1,
                "msg": "用户不存在"
            }
        # 删除权限
        await userdb.execute("DELETE FROM vfs WHERE username = ?", True, (username,))
        await userdb.execute("DELETE FROM `session` WHERE username = ?", True, (username,))
        return {
            "code": 0,
            "msg": ""
        }

    @app.route.post("/user/change_passwd", level=2)
    async def change_password_admin(user: User, username: str, passwd: str):  # 管理员修改用户密码
        if (not await app.checker.check_func_permission(user, 2, "user")):
            raise HTTPException(status_code=403)
        # 更新用户密码
        ret = await userdb.execute_rc("UPDATE users SET password = ? WHERE username = ?", True, (userdb.hash_password(passwd), username))
        if (ret == 0):  # 没有受影响的行
            return {
                "code": 1,
                "msg": "用户不存在"
            }
        return {
            "code": 0,
            "msg": ""
        }

    @app.route.get("/user/permission", level=2)
    async def get_all_permission(user: User, username: str):  # 获取用户权限
        if (not await app.checker.check_func_permission(user, 2, "user")):
            raise HTTPException(status_code=403)
        rets = await userdb.execute("SELECT * FROM vfs WHERE username = ?", False, (username,))
        return {
            "code": 0,
            "msg": "",
            "data": [(i[2], i[3], i[0]) for i in rets]  # 整理格式
        }

    @app.route.post("/user/permission", level=2)
    # 设置用户权限(新增/修改)
    async def set_permission(user: User, username: str, path: str, permission: int):
        if (path == "" or path[0] != "/"):
            return {
                "code": 1,
                "msg": "路径不合法"
            }
        if (not await app.checker.check_func_permission(user, 2, "user")):
            raise HTTPException(status_code=403)
        await vfs.set_permission(username, path, permission)  # 设置权限
        return {
            "code": 0,
            "msg": ""
        }

    @app.route.post("/user/permission/remove", level=2)
    async def del_permission(user: User, username: str, dbid: int):  # 删除用户权限
        if (not await app.checker.check_func_permission(user, 2, "user")):
            raise HTTPException(status_code=403)
        rowcount = await userdb.execute_rc("DELETE FROM vfs WHERE username = ? AND `id` = ?", True, (username, dbid))
        if (username in vfs.users_permission_cache):
            del vfs.users_permission_cache[username]
        if (rowcount == 0):
            return {
                "code": 1,
                "msg": "用户不存在"
            }
        return {
            "code": 0,
            "msg": ""
        }

    @app.route.get("/user/permissioninfo", level=2)
    async def get_permission_info(user: User):  # 获取权限信息
        if (not await app.checker.check_func_permission(user, 2, "user")):
            raise HTTPException(status_code=403)
        return {
            "code": 0,
            "msg": "",
            "data": plugin.permission_info_lst
        }

    @app.route.post("/change_passwd_user", level=1)
    async def change_password_user(user: User, passwd: str):  # 用户修改密码
        ret = await userdb.execute_rc("UPDATE users SET password = ? WHERE username = ?", True, (userdb.hash_password(passwd), user.username))
        if (ret == 0):
            return {
                "code": 1,
                "msg": "用户不存在"
            }
        return {
            "code": 0,
            "msg": ""
        }
